import {query, queryMenu, queryRoleMenu, remove, saveOrUpdate, saveRoleMenu} from './service';

export default {
  namespace: 'role',

  state: {
    data: {},
    loading: true,
    menuData:{rows:[]}
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(query, payload);
      if(response.resultCode==="1") {
        yield put({
          type: 'save',
          payload: response,
        });
        yield put({
          type: 'changeLoading',
          payload: false,
        });
      }
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(saveOrUpdate, payload);
      if(response.resultCode==="1") {
        yield put({ type: 'fetch' })
      }
      if (callback) callback(response);
    },
    *edit({ payload, callback }, { call, put }) {
      const response = yield call(saveOrUpdate, payload);
      if(response.resultCode==="1") {
        yield put({ type: 'fetch' })
      }
      if (callback) callback(response);
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(remove, payload);
      if(response.resultCode==="1"){
        yield put({ type: 'fetch' })
      }
      if (callback) callback(response);
    },
    *queryMenu({ payload }, { call, put }) {
      const response = yield call(queryMenu, payload);
      if(response.resultCode==="1") {
        yield put({
          type: 'saveMenu',
          payload: response,
        });
      }
    },
    *queryRoleMenu({ payload, callback }, { call }) {
      const response = yield call(queryRoleMenu, payload);
      if (callback) callback(response);
    },
    *saveRoleMenu({ payload, callback }, { call }) {
      const response = yield call(saveRoleMenu, payload);
      if (callback) callback(response);
    },
  },

  reducers: {
    saveMenu(state, action) {
      return {
        ...state,
        menuData: action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
  },
};
